import 'dart:convert';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';

class FileWidget extends StatefulWidget {
  FileWidget({this.title}) : super();
  final String ?title;

  @override
  State<StatefulWidget> createState() {
    return FileState();
  }
}

class FileState extends State<FileWidget> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title??""),
        ),
        body: Container(
            padding: EdgeInsets.all(15),
            alignment: Alignment.center,
            child: Column(
              children: [
                GestureDetector(
                  child: DecoratedBox(
                    decoration: BoxDecoration(
                        gradient: LinearGradient(
                            colors: [Colors.deepOrange, Colors.deepPurple]),
                        //背景渐变
                        borderRadius: BorderRadius.circular(3.0),
                        boxShadow: [
                          BoxShadow(
                              color: Colors.grey,
                              offset: Offset(2.0, 2.0),
                              blurRadius: 4.0)
                        ]),
                    child: Center(
                      heightFactor: 2,
                      child: Text(
                        "创建文件夹",
                        style: TextStyle(fontSize: 15, color: Colors.white),
                      ),
                    ),
                  ),
                  onTap: () {
                    _createDir();
                  },
                ),
                SizedBox(
                  height: 30,
                ),
                GestureDetector(
                  child: DecoratedBox(
                    decoration: BoxDecoration(
                        gradient: LinearGradient(
                            colors: [Colors.deepOrange, Colors.deepPurple]),
                        //背景渐变
                        borderRadius: BorderRadius.circular(3.0),
                        boxShadow: [
                          BoxShadow(
                              color: Colors.grey,
                              offset: Offset(2.0, 2.0),
                              blurRadius: 4.0)
                        ]),
                    child: Center(
                      heightFactor: 2,
                      child: Text(
                        "遍历文件夹",
                        style: TextStyle(fontSize: 15, color: Colors.white),
                      ),
                    ),
                  ),
                  onTap: () {
                    _dirList();
                  },
                ),
                SizedBox(
                  height: 30,
                ),
                GestureDetector(
                  child: DecoratedBox(
                    decoration: BoxDecoration(
                        gradient: LinearGradient(
                            colors: [Colors.deepOrange, Colors.deepPurple]),
                        //背景渐变
                        borderRadius: BorderRadius.circular(3.0),
                        boxShadow: [
                          BoxShadow(
                              color: Colors.grey,
                              offset: Offset(2.0, 2.0),
                              blurRadius: 4.0)
                        ]),
                    child: Center(
                      heightFactor: 2,
                      child: Text(
                        "创建文件,写数据",
                        style: TextStyle(fontSize: 15, color: Colors.white),
                      ),
                    ),
                  ),
                  onTap: () {
                    _createFile();
                  },
                ),
                SizedBox(
                  height: 30,
                ),
                GestureDetector(
                  child: DecoratedBox(
                    decoration: BoxDecoration(
                        gradient: LinearGradient(
                            colors: [Colors.deepOrange, Colors.deepPurple]),
                        //背景渐变
                        borderRadius: BorderRadius.circular(3.0),
                        boxShadow: [
                          BoxShadow(
                              color: Colors.grey,
                              offset: Offset(2.0, 2.0),
                              blurRadius: 4.0)
                        ]),
                    child: Center(
                      heightFactor: 2,
                      child: Text(
                        "读取json数据",
                        style: TextStyle(fontSize: 15, color: Colors.white),
                      ),
                    ),
                  ),
                  onTap: () {
                    _loadAsset(context);
                  },
                ),
              ],
            )));
  }

  /// 创建文件夹
  _createDir() async {
    Directory? documentsDirectory = await getExternalStorageDirectory();
    //Platform.pathSeparator表示路径分隔符，对于Android和iOS来说表示‘/’。
    String path = '${documentsDirectory?.path}${Platform.pathSeparator}flutter';
    var dir = Directory(path);
    var exist = dir.existsSync();
    if (exist) {
      print('当前文件夹已经存在 ' + path);
    } else {
      var result = await dir.create();
      print('$result');
    }
  }

  ///遍历文件夹
  _dirList() async {
    Directory ?documentsDirectory = await getExternalStorageDirectory();
    String path = '${documentsDirectory?.path}${Platform.pathSeparator}';

    Stream<FileSystemEntity> fileList = Directory(path).list(recursive: true);

    await for (FileSystemEntity fileSystemEntity in fileList) {
      //判断文件类型
      FileSystemEntityType type =
          FileSystemEntity.typeSync(fileSystemEntity.path);
      print('$fileSystemEntity' + " 类型 " + type.toString());
    }
  }

  ///创建一个文件
  _createFile() async {
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path =
        '${documentsDirectory.path}${Platform.pathSeparator}kun${Platform.pathSeparator}file.txt';
    var file = await File(path).create(recursive: true);
    file.writeAsBytes(Utf8Encoder().convert("老孟 Flutter bytes 格式"));
    print('文件创建是否成功 ' + file.path);
  }

  ///读取 asset 文件
  _loadAsset(BuildContext context) async {
    var jsonStr = await DefaultAssetBundle.of(context)
        .loadString('assets/json/data.json');
    var list = json.decode(jsonStr);
    print('list '+list.toString());
    // list.forEach((element) {
    //   print('$element');
    // });
  }
}
